package com.yuanchu.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.yuanchu.auth.dto.AuthParamsDto;
import com.yuanchu.auth.dto.ShopUserExtend;
import com.yuanchu.auth.service.AuthService;
import com.yuanchu.common.exception.YuanChuException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @version: 1.0
 * @Author: adan
 * @description: 自定义UserDetailsService用来对接Spring Security
 * @date: 2024-01-15 21:38
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {


    @Autowired
    ApplicationContext applicationContext;

    /**
     * 查询用户信息组成用户身份信息
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        AuthParamsDto authParamsDto = null;
        try {
            //将认证参数转为AuthParamsDto类型
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}", s);
            throw new YuanChuException("认证请求数据格式不对");
        }
        //认证方法
        String authType = authParamsDto.getAuthType();
        if (authType == null || authType.isEmpty()) {
            // throw new YuanChuException("认证类型不能为空");
            if (authParamsDto.getUsername() != null && authParamsDto.getPassword() != null) {
                authType = "password";
            } else if (authParamsDto.getCellphone() != null) {
                authType = "sms";
            }
        }
        AuthService authService =  applicationContext.getBean(authType + "_authService",AuthService.class);
        //开始认证
        ShopUserExtend user = authService.execute(authParamsDto);
        return getUserPrincipal(user);
    }



    /**
     * 获取用户权限
     * @param user 用户信息
     * @return userDetails
     */
    public UserDetails getUserPrincipal(ShopUserExtend user){
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection

        String[] authorities = {"p1"};
        String password = user.getPassword();
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(user);
        //创建UserDetails对象
        return User.withUsername(userString).password(password).authorities(authorities).build();
    }

/*
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        AuthParamsDto authParamsDto = null;
        try {
            //将认证参数转为AuthParamsDto类型
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}", s);
            throw new YuanChuException("认证请求数据格式不对");
        }
        //认证方法
        String authType = authParamsDto.getAuthType();
        if (authType == null || authType.isEmpty()) {
            // throw new YuanChuException("认证类型不能为空");
            if (authParamsDto.getUsername() != null && authParamsDto.getPassword() != null) {
                authType = "password";
            } else if (authParamsDto.getCellphone() != null) {
                authType = "sms";
            }
        }
        AuthService authService =  applicationContext.getBean(authType + "_authService",AuthService.class);
        //开始认证
        ShopUserExtend user = authService.execute(authParamsDto);
        return getUserPrincipal(user);

    }
*/



    /*@Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        AuthParamsDto authParamsDto = null;
        try {
            //将认证参数转为AuthParamsDto类型
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }
        //账号
        String username = authParamsDto.getUsername();
        YoshopStoreUserEntity user = shopsUserService.getOne(new LambdaQueryWrapper<YoshopStoreUserEntity>().eq(YoshopStoreUserEntity::getUserName, username));
        if(user==null){
            //返回空表示用户不存在
            return null;
        }
        //取出数据库存储的正确密码
        String password  =user.getPassword();
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities = {"p1"};
        //将user对象转json
        String userString = JSON.toJSONString(user);
        //创建UserDetails对象
        UserDetails userDetails = User.withUsername(userString).password(password).authorities(authorities).build();

        return userDetails;
    }*/


    /*@Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 根据名称获取用户
        YoshopStoreUserEntity user = shopsUserService.getOne(new LambdaQueryWrapper<YoshopStoreUserEntity>().eq(YoshopStoreUserEntity::getUserName, s));
        if (user == null){
            //返回空表示用户不存在
            return null;
        }
        //取出数据库存储的正确密码
        String password  =user.getPassword();
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities = {"p1"};
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(user);
        //创建UserDetails对象,权限信息待实现授权功能时再向UserDetail中加入
        UserDetails userDetails = User.withUsername(userString).password(password).authorities(authorities).build();

        return userDetails;
    }*/


}
